import React from 'react'
import { useLocation, useHistory } from 'react-router-dom'
import { getToken } from '@/utils/auth'
import { useDispatch, useSelector } from 'react-redux'
import { getUserInfo, userRemoveInfo } from '@/store/usersSlice'
import { permissionFilter } from '@/store/permissionRouterSlice'

/**
 * @description 高阶组件控制路由跳转
 */
const authorityComponent = function ( WrappedComponent ) {

    return function() {
        
        let history = useHistory()
        const dispatch = useDispatch()
        let { pathname } = useLocation()

        React.useEffect(() => {

            // console.log('路由发生变化', location)
            const hasToken = getToken()

            if( hasToken ) {
                if( pathname === '/login' ) {

                    history.push('/')

                }else{

                    const asyncFn = async () => {
                        try{
                         //获取用户信息并存储在redux中
                          await dispatch(getUserInfo())
                           //获取用户权限 过滤出有权限访问的路由

                          //判断访问路径是否有权限，若没有则跳转到404

                          //跳转到指定路径
                          
                        }catch(error) {
                            //清空redux相关信息 回到登录界面
                            dispatch( userRemoveInfo )
                            history.push( '/login' )
                        }
        
                     
                    }

                    asyncFn()


                    // history.push( '/404' )
                    // console.log('pathname', pathname)
                }
            }else{
                history.push('/login')
            }

        }, [pathname ])



        let { role } = useSelector( (state) => state.user)
        React.useEffect(() => {
             dispatch( permissionFilter( role ) )
            console.log('role', role)
            console.log(pathname)
        })
        



        return <WrappedComponent />
    }
}

export default authorityComponent